package com.bj58.mis.bigdata.mdp.sys.controller;

import com.bj58.mis.bigdata.mdp.sys.common.consts.ResultCodeConsts;
import com.bj58.mis.bigdata.mdp.sys.common.result.ResultBean;
import com.bj58.mis.bigdata.mdp.sys.util.JsonUtil;
import com.bj58.mis.bigdata.mdp.sys.vo.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/bigDataSSO")
public class BigDataSSOController extends SSOController {



    @GetMapping("/login")
    public ResultBean login(@RequestParam("cdp_key") String cdp_key, @RequestParam("cdp_user") String cdp_user){
        String url = "http://bigdata.58.com/sso/check?cdp_key="+cdp_key+"&cdp_user="+cdp_user;
        System.out.println("loginUrl:"+url);
        String strResp = restTemplate.getForObject(url, String.class);
        Map<String, Object> resp = JsonUtil.fromJson(strResp, Map.class);
        if(((Number)resp.get("result")).intValue()==1){
            LoginUser loginUser = JsonUtil.fromJson(resp.get("data").toString(), LoginUser.class);
            String token = saveLoginUserToRedis(loginUser);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("loginUser", loginUser);
            return ResultBean.success(data, "登录成功!");
        }else{
            return ResultBean.error((String)resp.get("data"));
        }
    }

    @GetMapping("/currLoginUser")
    public ResultBean currLoginUser(@RequestParam("token") String token){
        String key = REDIS_TOKEN_KEY+token;
        String jsonLoginUser = redisTemaplte.opsForValue().get(key);
        if(jsonLoginUser!=null){
            LoginUser loginUser = JsonUtil.fromJson(jsonLoginUser, LoginUser.class);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("loginUser", loginUser);
            return ResultBean.success(data, "OK!");
        }else{
            return ResultBean.error(ResultCodeConsts.NOT_LOGIN, "没有登录信息");
        }

    }

}
